package com.tz.tools;

import com.tz.tools.constant.StringConstPool;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

/**
 * 枚举类工具
 *
 * @author zjc
 * @since 2022/11/25 15:13
 */
public class EnumTools {

    /**
     * 枚举常量信息转成字符串
     *
     * @param enumClass 枚举类
     * @return 字符串
     */
    public static String enumToString(Class<? extends Enum<?>> enumClass) {
        Enum<?>[] enumConstants = enumClass.getEnumConstants();
        Field[] fields = enumClass.getDeclaredFields();
        List<String> enumStrList = new ArrayList<>();
        for (Enum<?> enum1 : enumConstants) {
            List<String> fieldValueList = new ArrayList<>();
            for (Field field : fields) {
                //排除静态字段
                if (!Modifier.isStatic(field.getModifiers())) {
                    Object value;
                    try {
                        value = FieldUtils.readField(enum1, field.getName(), true);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                    fieldValueList.add(String.valueOf(value));
                }
            }
            enumStrList.add(StringUtils.join(fieldValueList, StringConstPool.DASH));
        }
        return StringUtils.join(enumStrList, StringConstPool.COMMA);
    }
}